var JWT = require('../public/javascripts/jwt');
var express = require('express');
var router = express.Router();
const bcryptjs = require('bcryptjs');
const db = require('../db/index');

/* GET user listing. */
router.post('/login', function(req, res, next) {
  const sql = `select * from user where username="${req.body.username}"`;
  db.query(sql, (err, results) => {
    if (err) {
      res.send({
        code: 500,
        msg: err
      })
    } else if (results.length > 0) {
      if (bcryptjs.compareSync(req.body.password, results[0].password)) {
        let token = JWT.createToken({ username: req.body.username, id: results[0].id }, '1day');
        res.header('Authorization', 'Bearer ' + token);
        res.send({
          code: 200,
          data: {
            token: 'Bearer ' + token
          },
          msg: '登录成功'
        });
      } else {
        res.send({
          code: 500,
          msg: '密码错误'
        })
      }
    } else {
      res.send({
        code: 500,
        msg: '账号错误'
      })
    }
  });
});

module.exports = router;
